//
//  GYLift.m
//  GoodLuck
//
//  Created by apple on 2018/2/28.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYLife.h"
#import "GYNetWorkTools.h"

@implementation GYLife

+ (void)loadLifeData:(NSString *)gc_id success:(void (^)(NSArray * _Nullable, NSError * _Nullable))finish {
    NSMutableArray *lifes = [NSMutableArray array];
    [EasyLodingView showLodingText:@"正在加载..."];
    [GYNetWorkTools requestSubclassCategory:gc_id success:^(NSDictionary *obj) {
        NSString *code = [obj objectForKey:@"code"];
        if ([code intValue] == 200) {
            [EasyLodingView hidenLoding];
            NSDictionary *datas = [obj objectForKey:@"datas"];
            NSArray *class_list = [datas objectForKey:@"class_list"];
            for (NSDictionary *dic in class_list) {
                
                //开始解析
                GYLife *life = [[GYLife alloc] initWithDic:dic];
                [lifes addObject:life];
            }
            
            finish(lifes,nil);
        }else {
            [EasyTextView showText:@"加载数据出错,请重新加载!"];
            [EasyLodingView hidenLoding];
            NSLog(@"网络请求数据出错=====%@",[obj objectForKey:@"msg"]);
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"加载数据出错,请重新加载!"];
        [EasyLodingView hidenLoding];
        finish(nil,error);
    }];
}

+ (NSArray *)analysisData:(NSArray *)source {
    NSMutableArray *array = [NSMutableArray array];
    for (NSDictionary *dic in source) {
        GYLife *life = [[GYLife alloc] initWithDic:dic];
        [array addObject:life];
    }
    
    return array;
}

- (instancetype)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        
        [self setValuesForKeysWithDictionary:dic];
    }
    return self;
}

- (void)setValue:(id)value forKey:(NSString *)key {
    [super setValue:value forKey:key];
    
    if ([key isEqualToString:@"child"]) {
        if (value == nil) {
            return;
        }else {
            self.child = [GYLife analysisData:value];
        }
    }
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    //NSLog(@"key =====%@",key);
}

- (NSString *)description {
    NSArray *keys = @[@"gc_id",@"gc_name",@"child"];
    return [NSString stringWithFormat:@"%@",[self dictionaryWithValuesForKeys:keys]];
}
@end
